package com.cyc.quick.service.impl;

import cn.hutool.system.UserInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyc.quick.exception.ProjectException;
import com.cyc.quick.mapper.SysUserMapper;
import com.cyc.quick.pojo.entity.SysUser;
import com.cyc.quick.pojo.vo.UserInfoVO;
import com.cyc.quick.pojo.vo.UserReq;
import com.cyc.quick.service.IDictService;
import com.cyc.quick.service.ISysUserService;
import com.cyc.quick.pojo.vo.SysUserAddVO;
import com.cyc.quick.util.BeanHelper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chenyunchang
 * @since 2021-01-19
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {



    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IDictService dictService;

    /**
     * @param sysUserAddVO 添加用户对象
     * @param request
     * @author chenyunchang
     * @description 添加用户
     * @date 2021-01-20 09:26:08
     */
    @Override
    public void register(SysUserAddVO sysUserAddVO, HttpServletRequest request) {
        //1. 校验手机号是否重复
        String phone = sysUserAddVO.getPhone();
        log.info("注册用户填写的信息: " + sysUserAddVO);
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getPhone, phone);
        SysUser sysUserDb = this.getOne(lambdaQueryWrapper);
        if (sysUserDb != null) {
            throw new ProjectException("400", "手机号已存在, 请确认手机号");
        }
        SysUser sysUser = BeanHelper.copyProperties(sysUserAddVO, SysUser.class);
        this.save(sysUser);
    }

    /**
     * @author chenyunchang
     * @description 分页查询用户
     * @param userReq 筛选用户对象
     * @return PageInfo<UserInfoVO>
     * @date 2021-01-26 10:58:50
     */
    @Override
    public PageInfo<UserInfoVO> findPage(UserReq userReq) {
        PageHelper.startPage(userReq);
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(userReq.getUserId() != null, SysUser::getId, userReq.getUserId())
                .like(userReq.getRealName() != null, SysUser::getRealName, userReq.getRealName());
        List<SysUser> sysUserList = this.list(queryWrapper);
        List<UserInfoVO> userInfoVOList = BeanHelper.copyWithCollection(sysUserList, UserInfoVO.class);
        return new PageInfo<>(userInfoVOList);
    }
}
